using System.IO;
using System.Xml;
using System.Xml.Linq;
using EnvDTE;

namespace Microsoft.WowAddonStudio.ProjectRefactor
{
    /// <summary>
    /// Merges source code changes into Code Window.
    /// </summary>
    public sealed class FrameXmlDocumentMerger : BaseFrameXmlMerger
    {
        private readonly TextDocument document;

		/// <summary>
		/// Initializes a new instance of the <see cref="FrameXmlDocumentMerger"/> class.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		/// <param name="document">The document.</param>
        public FrameXmlDocumentMerger(string fileName, TextDocument document)
            : base(fileName)
        {
            this.document = document;
        }

        #region IFrameXmlMerger Members

		/// <summary>
		/// Merges new text into file.
		/// </summary>
		/// <param name="newXml">The new XML.</param>
        public override void Merge(string newXml)
        {
            EditPoint editPoint = document.CreateEditPoint(document.StartPoint);
            editPoint.ReplaceText(document.EndPoint, newXml,
                                  (int) vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines);
        }

        /// <summary>
        /// Merges the new Lua code file name into the specified FramXml file as a refernce.
        /// </summary>
        /// <param name="frameXmlPath">Path of FrameXml file.</param>
        /// <param name="luaCodeFilePath">Path of Lua code file.</param>
        public override void MergeFrameName(string frameXmlPath, string luaCodeFilePath)
        {
            base.MergeFrameName(frameXmlPath, luaCodeFilePath);

            string luaFileName = Path.GetFileName(luaCodeFilePath);
            EditPoint editPoint = document.CreateEditPoint(document.StartPoint);
            string xml = editPoint.GetText(document.EndPoint);
            var sourceReader = new StringReader(xml);

            using (XmlReader reader = XmlReader.Create(sourceReader))
            {
                XElement root = XElement.Load(reader);
                ReplaceScriptFileAttribute(root, reader.NameTable, luaFileName);
                Merge(root.ToString());
            }

            if (!document.DTE.ItemOperations.IsFileOpen(frameXmlPath, Constants.vsViewKindTextView))
                document.DTE.ItemOperations.OpenFile(frameXmlPath, Constants.vsViewKindTextView);
        }

        #endregion
    }
}